import axios, { AxiosError, type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import errorCode from '@/utils/errorCode'

/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout: 500000
})

// 添加请求拦截器
service.interceptors.request.use((config) => {
  const token = sessionStorage.getItem('Authorization')
  const company = sessionStorage.getItem('company')
  const lang = sessionStorage.getItem('lang')
  if (token) {
    ;(config.headers as AxiosRequestHeaders).Authorization = token
  }
  if (company && company !== 'undefined') {
    ;(config.headers as AxiosRequestHeaders).company = JSON.parse(company)[0].code
    ;(config.headers as AxiosRequestHeaders).version = 'lhw'
  }
  if (lang && lang !== 'undefined') {
    ;(config.headers as AxiosRequestHeaders)['Accept-Language'] = JSON.parse(lang)
  }
  return config
})

// 添加响应拦截器
// service.interceptors.response.use(
//   /* 约束一下response */
//   (response: any) => {
//     let res = response.data,m
//     if (res.code === 3) {
//       ElMessage.warning('登录超时请重新登录')
//       sessionStorage.removeItem('Authorization')
//       setTimeout(() => {
//         window.location.href = '/login'
//       }, 1000)
//     }
//     return res
//   }
// )
// 响应拦截器

// 是否显示重新登录
export let isRelogin = { show: false }

service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            isRelogin.show = false
            ElMessage.warning('登录超时请重新登录')
            sessionStorage.removeItem('Authorization')
            setTimeout(() => {
              window.location.href = '/login'
            }, 1000)
          })
          .catch(() => {
            isRelogin.show = false
          })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else {
      return Promise.resolve(res.data)
    }
  },
  (error) => {
    console.log('err' + error)
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service
